/* eslint-disable no-console */
<template>
  <div>
    <div>
      <home-header></home-header>
      <home-swiper :list="swiperList"></home-swiper>
      <home-icons :list="iconList"></home-icons>
      <home-recommend :list="recommendList"></home-recommend>
      <home-weekend :list="weekendList"></home-weekend>
    </div>
  </div>
</template>

<script>
import HomeHeader from "./components/Header";
import HomeSwiper from "./components/Swiper";
import HomeIcons from "./components/Icons";
import HomeRecommend from "./components/Recommend";
import HomeWeekend from "./components/Weekend";
import { mapState } from "vuex";
import axios from "axios";
export default {
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekend
  },
  data() {
    return {
      name: "Home",
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: [],
      lastCity: ""
    };
  },
  computed: {
    ...mapState(["city"])
  },
  methods: {
    getHomeInfo() {
      // 页面一挂载完成就去请求 ajax 数据，axios 返回的结果是 promise 对象 所以可以用 then
      axios
        .get("/api/index.json?city=" + this.city)
        .then(this.getHomeInfoSucc, this.getHomeInfoError);
    },
    getHomeInfoSucc(res) {
      // 数据获取成功就打印出来
      console.log(res);
      res = res.data;
      if (res.ret && res.data) {
        const data = res.data;
        this.swiperList = data.swiperList;
        this.iconList = data.iconList;
        this.recommendList = data.recommendList;
        this.weekendList = data.weekendList;
      }
    },
    getHomeInfoError(res) {
      console.log("获取失败 ");
      console.log(res);
    }
  },
  mounted() {
    this.lastCity = this.city;
    this.getHomeInfo();
  },
  activated() {
    // 当 App.vue 设置了 keep-alive 属性时，就会有这个生命周期
    // 表示这个生命周期不受  keep-alive 属性影响，页面重新被显示时依然会执行
    if (this.lastCity !== this.city) {
      this.lastCity = this.city;
      this.getHomeInfo();
    }
  }
};
</script>
